package cn.com.gensoft.app.core.mybatis;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;

import java.time.Instant;

/**
 * 全局属性自动注入handler
 * @author hlj
 */
public class CommonMetaObjectHandler extends MetaObjectHandler {

    private final String CREATED_BY = "createdBy";
    private final String CREATED_DATE = "createdDate";
    private final String LAST_MODIFIED_BY = "lastModifiedBy";
    private final String LAST_MODIFIED_DATE = "lastModifiedDate";

    /**
     * 新增填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createBy = getFieldValByName(CREATED_BY, metaObject);
        Object createDate = getFieldValByName(CREATED_DATE, metaObject);
        Object lastModifiedBy = getFieldValByName(LAST_MODIFIED_BY, metaObject);
        Object lastModifiedDate = getFieldValByName(LAST_MODIFIED_DATE, metaObject);
        //获取当前登录用户
        /*UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
            .getAuthentication()
            .getPrincipal();*/
        String user = null;//SecurityUtils.getSubject().getPrincipal();
        if (null == user) {
            user = "admin";
        }
        if (null == createBy) {
            setFieldValByName(CREATED_BY, user, metaObject);
        }
        if (null == lastModifiedBy) {
            setFieldValByName(LAST_MODIFIED_BY, user, metaObject);
        }
        //获取系统时间
        Instant date = Instant.now();
        if (null == createDate) {
            setFieldValByName(CREATED_DATE, date, metaObject);
        }
        if (null == lastModifiedDate) {
            setFieldValByName(LAST_MODIFIED_DATE, date, metaObject);
        }
    }

    /**
     * 更新填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        insertFill(metaObject);
    }
}
